package com.copd.service.impl;

import com.copd.dto.BackupDataQueryRequest;
import com.copd.entity.DoctorOperationDetail;
import com.copd.entity.DoctorOperationLog;
import com.copd.entity.User;
import com.copd.mapper.BackupDataMapper;
import com.copd.mapper.DoctorOperationLogMapper;
import com.copd.mapper.PatientMapper;
import com.copd.mapper.UserMapper;
import com.copd.service.BackupDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class BackupDataServiceImpl implements BackupDataService {
    private static final Logger logger = LoggerFactory.getLogger(BackupDataServiceImpl.class);
    
    @Autowired
    private BackupDataMapper backupDataMapper;
    
    @Autowired
    private PatientMapper patientMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private DoctorOperationLogMapper doctorOperationLogMapper;

    @Override
    public Map<String, Object> queryBackupData(BackupDataQueryRequest request, Integer doctorId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 参数校验
            if (request == null) {
                throw new IllegalArgumentException("请求参数不能为空");
            }
            
            // 获取分页参数
            Integer page = request.getPage() != null ? request.getPage() : 1;
            Integer size = request.getSize() != null ? request.getSize() : 10;
            int offset = (page - 1) * size;
            
            // 查询结果列表
            List<Map<String, Object>> backupData = new ArrayList<>();
            long total = 0;
            
            // 根据查询的表名类型进行不同查询
            String tableName = request.getTableName();
            if (tableName == null || tableName.isEmpty()) {
                // 如果未指定表名，返回空列表
                result.put("backupData", backupData);
                result.put("total", total);
                result.put("page", page);
                result.put("size", size);
                result.put("backupTables", getBackupTablesList());
                
                // 添加医生信息
                if (doctorId != null) {
                    result.put("doctorInfo", getDoctorInfo(doctorId));
                }
                
                return result;
            }
            
            // 拼接完整表名（如果需要）
            if (!tableName.endsWith("_backup")) {
                tableName = tableName + "_backup";
            }
            
            switch (tableName) {
                case "patient_info_backup":
                    backupData = backupDataMapper.selectPatientInfoBackups(
                            request.getPatientId(),
                            null,
                            null,
                            null,
                            offset,
                            size
                    );
                    total = backupDataMapper.countBackupData(
                            "patient_info_backup",
                            request.getPatientId(),
                            null,
                            null,
                            null
                    );
                    break;
                case "diagnosis_records_backup":
                    backupData = backupDataMapper.selectDiagnosisRecordsBackups(
                            request.getPatientId(),
                            null,
                            null,
                            null,
                            offset,
                            size
                    );
                    total = backupDataMapper.countBackupData(
                            "diagnosis_records_backup",
                            request.getPatientId(),
                            null,
                            null,
                            null
                    );
                    break;
                case "examination_items_backup":
                    backupData = backupDataMapper.selectExaminationItemsBackups(
                            request.getPatientId(),
                            null,
                            null,
                            null,
                            offset,
                            size
                    );
                    total = backupDataMapper.countBackupData(
                            "examination_items_backup",
                            request.getPatientId(),
                            null,
                            null,
                            null
                    );
                    break;
                case "treatment_plans_backup":
                    backupData = backupDataMapper.selectTreatmentPlansBackups(
                            request.getPatientId(),
                            null,
                            null,
                            null,
                            offset,
                            size
                    );
                    total = backupDataMapper.countBackupData(
                            "treatment_plans_backup",
                            request.getPatientId(),
                            null,
                            null,
                            null
                    );
                    break;
                case "discharge_records_backup":
                    backupData = backupDataMapper.selectDischargeRecordsBackups(
                            request.getPatientId(),
                            null,
                            null,
                            null,
                            offset,
                            size
                    );
                    total = backupDataMapper.countBackupData(
                            "discharge_records_backup",
                            request.getPatientId(),
                            null,
                            null,
                            null
                    );
                    break;
                default:
                    throw new IllegalArgumentException("不支持的备份表: " + tableName);
            }
            
            // 对每个记录添加表描述信息
            for (Map<String, Object> record : backupData) {
                record.put("tableName", tableName);
                record.put("tableDescription", getTableDescription(tableName));
            }
            
            result.put("backupData", backupData);
            result.put("total", total);
            result.put("page", page);
            result.put("size", size);
            result.put("backupTables", getBackupTablesList());
            
            // 添加医生信息
            if (doctorId != null) {
                result.put("doctorInfo", getDoctorInfo(doctorId));
            }
            
            // 添加患者信息（如果指定了患者ID）
            if (request.getPatientId() != null) {
                result.put("patientInfo", getPatientInfo(request.getPatientId()));
            }
            
            // 添加相关的操作日志信息
            if (request.getPatientId() != null || doctorId != null) {
                // 获取相关的操作日志（限制前5条）
                Map<String, Object> operationLogs = getBackupOperationLogs(
                    doctorId, 
                    request.getPatientId(), 
                    request.getTableName(),
                    request.getOperationType(),
                    request.getStartTime(),
                    request.getEndTime(), 
                    1, 5
                );
                result.put("recentOperations", operationLogs.get("logs"));
            }
            
            return result;
        } catch (Exception e) {
            logger.error("查询备份数据失败", e);
            throw new RuntimeException("查询备份数据失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getBackupTablesInfo(Integer doctorId) {
        Map<String, Object> result = new HashMap<>();
        result.put("backupTables", getBackupTablesList());
        
        // 添加医生信息
        if (doctorId != null) {
            result.put("doctorInfo", getDoctorInfo(doctorId));
        }
        
        // 添加简略的操作日志统计
        Map<String, Object> operationStats = getBackupOperationSummary(doctorId);
        result.put("operationStats", operationStats);
        
        return result;
    }
    
    /**
     * 获取备份操作的统计摘要
     */
    private Map<String, Object> getBackupOperationSummary(Integer doctorId) {
        Map<String, Object> stats = new HashMap<>();
        try {
            // 获取近期的操作日志（最多10条）
            Map<String, Object> recentLogs = getBackupOperationLogs(doctorId, null, null, null, null, null, 1, 10);
            stats.put("recentLogs", recentLogs.get("logs"));
            stats.put("totalLogs", recentLogs.get("total"));
            
            // 为每张备份表提供操作统计
            List<Map<String, String>> backupTables = getBackupTablesList();
            List<Map<String, Object>> tableStats = new ArrayList<>();
            
            for (Map<String, String> table : backupTables) {
                String tableName = table.get("originalName");
                Map<String, Object> tableStat = new HashMap<>();
                tableStat.put("tableName", tableName);
                tableStat.put("tableNameBackup", table.get("name"));
                tableStat.put("description", table.get("description"));
                
                // 查询该表最近的一条操作记录
                Map<String, Object> tableOperation = getBackupOperationLogs(
                    doctorId, null, tableName, null, null, null, 1, 1);
                
                List<DoctorOperationLog> logs = (List<DoctorOperationLog>)tableOperation.get("logs");
                if (logs != null && !logs.isEmpty()) {
                    DoctorOperationLog latestLog = logs.get(0);
                    tableStat.put("lastOperation", latestLog);
                    // 获取操作的详情
                    List<DoctorOperationDetail> details = doctorOperationLogMapper.selectDetailsByLogId(latestLog.getLogId());
                    tableStat.put("operationDetails", details);
                }
                
                tableStats.add(tableStat);
            }
            
            stats.put("tableStats", tableStats);
            return stats;
        } catch (Exception e) {
            logger.error("获取备份操作统计失败", e);
            return new HashMap<>();
        }
    }
    
    @Override
    public Map<String, Object> getPatientInfo(Integer patientId) {
        if (patientId == null) {
            return null;
        }
        
        try {
            Map<String, Object> patientInfo = patientMapper.selectPatientById(patientId);
            if (patientInfo != null) {
                return patientInfo;
            }
            return null;
        } catch (Exception e) {
            logger.error("获取患者信息失败: {}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public Map<String, Object> getDoctorInfo(Integer doctorId) {
        if (doctorId == null) {
            return null;
        }
        
        try {
            User doctor = userMapper.selectById(doctorId);
            if (doctor != null && "doctor".equalsIgnoreCase(doctor.getRole())) {
                Map<String, Object> doctorInfo = new HashMap<>();
                doctorInfo.put("doctorId", doctor.getUserId());
                doctorInfo.put("doctorName", doctor.getUsername());
                doctorInfo.put("title", doctor.getTitle());
                doctorInfo.put("department", doctor.getDepartment());
                doctorInfo.put("yearsOfExperience", doctor.getYearsOfExperience());
                doctorInfo.put("certification", doctor.getCertification());
                doctorInfo.put("contactInfo", doctor.getContactInfo());
                return doctorInfo;
            }
            return null;
        } catch (Exception e) {
            logger.error("获取医生信息失败: {}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public Map<String, Object> getBackupOperationLogs(Integer doctorId, Integer patientId, String tableName, 
                                             String operationType, String startTime, String endTime, 
                                             Integer page, Integer size) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取分页参数
            int currentPage = page != null ? page : 1;
            int pageSize = size != null ? size : 10;
            int offset = (currentPage - 1) * pageSize;
            
            // 解析日期
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            
            if (startTime != null && !startTime.isEmpty()) {
                try {
                    startDate = dateFormat.parse(startTime);
                } catch (ParseException e) {
                    logger.warn("解析开始时间失败: {}", startTime);
                }
            }
            
            if (endTime != null && !endTime.isEmpty()) {
                try {
                    endDate = dateFormat.parse(endTime);
                } catch (ParseException e) {
                    logger.warn("解析结束时间失败: {}", endTime);
                }
            }
            
            // 设置操作结果条件 (暂不使用)
            Boolean operationResult = null;
            
            // 查询日志
            List<DoctorOperationLog> logs = doctorOperationLogMapper.selectLogs(
                doctorId,
                patientId,
                null, // doctorName
                null, // patientName
                operationType,
                operationResult,
                startDate,
                endDate,
                offset,
                pageSize
            );
            
            // 查询总数
            long total = doctorOperationLogMapper.countLogs(
                doctorId,
                patientId,
                null, // doctorName
                null, // patientName
                operationType,
                operationResult,
                startDate,
                endDate
            );
            
            // 处理表名筛选（因为表名存储在详情表中，需要额外处理）
            if (tableName != null && !tableName.isEmpty() && logs != null && !logs.isEmpty()) {
                List<DoctorOperationLog> filteredLogs = new ArrayList<>();
                
                for (DoctorOperationLog log : logs) {
                    List<DoctorOperationDetail> details = doctorOperationLogMapper.selectDetailsByLogId(log.getLogId());
                    boolean relevantToTable = false;
                    
                    for (DoctorOperationDetail detail : details) {
                        if (tableName.equals(detail.getTableName()) || 
                            (tableName + "_backup").equals(detail.getTableName())) {
                            relevantToTable = true;
                            break;
                        }
                    }
                    
                    if (relevantToTable) {
                        filteredLogs.add(log);
                    }
                }
                
                logs = filteredLogs;
                
                // 重新计算总数（简化处理，这里略过重新查询总数）
                total = filteredLogs.size();
            }
            
            // 为每条日志添加详情信息
            List<Map<String, Object>> enrichedLogs = new ArrayList<>();
            
            // 确保logs不为null，防止NPE
            if (logs != null) {
                for (DoctorOperationLog log : logs) {
                    Map<String, Object> logMap = new HashMap<>();
                    logMap.put("logId", log.getLogId());
                    logMap.put("doctorId", log.getDoctorId());
                    logMap.put("patientId", log.getPatientId());
                    logMap.put("operationType", log.getOperationType());
                    logMap.put("operationTime", log.getOperationTime());
                    logMap.put("operationResult", log.getOperationResult());
                    logMap.put("doctorName", log.getDoctorName());
                    logMap.put("patientName", log.getPatientName());
                    
                    // 获取操作详情
                    List<DoctorOperationDetail> details = doctorOperationLogMapper.selectDetailsByLogId(log.getLogId());
                    
                    // 添加处理后的详情
                    List<Map<String, Object>> processedDetails = new ArrayList<>();
                    for (DoctorOperationDetail detail : details) {
                        Map<String, Object> detailMap = new HashMap<>();
                        detailMap.put("detailId", detail.getDetailId());
                        detailMap.put("tableName", detail.getTableName());
                        detailMap.put("recordId", detail.getRecordId());
                        
                        // 优化操作详情显示 - 解析JSON并格式化
                        try {
                            String operationDetail = detail.getOperationDetail();
                            if (operationDetail != null && !operationDetail.isEmpty()) {
                                // 尝试解析为JSON对象
                                ObjectMapper objectMapper = new ObjectMapper();
                                try {
                                    // 如果是标准JSON格式，则进行格式化处理
                                    JsonNode jsonNode = objectMapper.readTree(operationDetail);
                                    
                                    // 根据JSON内容优化显示
                                    String formattedDetail = formatOperationDetailJson(jsonNode, detail.getTableName());
                                    detailMap.put("operationDetail", formattedDetail);
                                    
                                    // 保存原始JSON以备前端可能需要
                                    detailMap.put("rawOperationDetail", operationDetail);
                                } catch (Exception e) {
                                    // 如果不是标准JSON，则使用原始内容
                                    detailMap.put("operationDetail", operationDetail);
                                }
                            } else {
                                detailMap.put("operationDetail", "无操作详情");
                            }
                        } catch (Exception e) {
                            logger.warn("处理操作详情失败: {}", e.getMessage());
                            detailMap.put("operationDetail", detail.getOperationDetail());
                        }
                        
                        detailMap.put("tableDescription", getTableDescription(detail.getTableName()));
                        detailMap.put("isBackupTable", detail.getTableName().endsWith("_backup"));
                        processedDetails.add(detailMap);
                    }
                    
                    logMap.put("details", processedDetails);
                    enrichedLogs.add(logMap);
                }
            }
            
            // 确保即使查询结果为null，也会返回一个空数组而不是null
            result.put("logs", enrichedLogs);
            result.put("total", total);
            result.put("page", currentPage);
            result.put("size", pageSize);
            
            // 添加医生和患者信息（如果指定了ID）
            if (doctorId != null) {
                result.put("doctorInfo", getDoctorInfo(doctorId));
            }
            
            if (patientId != null) {
                result.put("patientInfo", getPatientInfo(patientId));
            }
            
            return result;
        } catch (Exception e) {
            logger.error("查询备份操作日志失败", e);
            // 即使发生异常，也确保返回一个有效的结果对象，避免前端报错
            result.put("logs", new ArrayList<>());
            result.put("total", 0);
            result.put("page", page != null ? page : 1);
            result.put("size", size != null ? size : 10);
            return result;
        }
    }

    /**
     * 获取备份表列表（带描述）
     */
    private List<Map<String, String>> getBackupTablesList() {
        List<Map<String, String>> backupTables = new ArrayList<>();
        
        // 定义备份表信息
        String[][] tablesInfo = {
            {"patient_info_backup", "patient_info", "患者基本信息表"},
            {"diagnosis_records_backup", "diagnosis_records", "患者诊断记录表"},
            {"examination_items_backup", "examination_items", "检查项目记录表"},
            {"treatment_plans_backup", "treatment_plans", "治疗项目记录表"},
            {"discharge_records_backup", "discharge_records", "出院建议记录表"}
        };
        
        for (String[] tableInfo : tablesInfo) {
            Map<String, String> tableMap = new HashMap<>();
            tableMap.put("name", tableInfo[0]);
            tableMap.put("originalName", tableInfo[1]);
            tableMap.put("description", tableInfo[2]);
            backupTables.add(tableMap);
        }
        
        return backupTables;
    }
    
    /**
     * 获取表描述
     */
    private String getTableDescription(String tableName) {
        Map<String, String> descMap = new HashMap<>();
        descMap.put("patient_info_backup", "患者基本信息表");
        descMap.put("diagnosis_records_backup", "患者诊断记录表");
        descMap.put("examination_items_backup", "检查项目记录表");
        descMap.put("treatment_plans_backup", "治疗项目记录表");
        descMap.put("discharge_records_backup", "出院建议记录表");
        
        // 同时支持非备份表名
        descMap.put("patient_info", "患者基本信息表");
        descMap.put("diagnosis_records", "患者诊断记录表");
        descMap.put("examination_items", "检查项目记录表");
        descMap.put("treatment_plans", "治疗项目记录表");
        descMap.put("discharge_records", "出院建议记录表");
        
        return descMap.getOrDefault(tableName, "");
    }
    
    /**
     * 格式化操作详情JSON
     */
    private String formatOperationDetailJson(JsonNode jsonNode, String tableName) {
        StringBuilder formatted = new StringBuilder();
        
        // 提取操作方法
        if (jsonNode.has("method")) {
            String method = jsonNode.get("method").asText();
            switch (method) {
                case "GET":
                    formatted.append("查询");
                    break;
                case "POST":
                    formatted.append("新增");
                    break;
                case "PUT":
                    formatted.append("更新");
                    break;
                case "DELETE":
                    formatted.append("删除");
                    break;
                default:
                    formatted.append(method);
            }
            formatted.append(" ");
        }
        
        // 添加表描述
        formatted.append(getTableDescription(tableName)).append(" ");
        
        // 添加参数信息
        if (jsonNode.has("args")) {
            JsonNode args = jsonNode.get("args");
            
            // 提取表名
            String detailTableName = args.has("tableName") ? args.get("tableName").asText() : tableName;
            
            // 提取字段信息
            if (args.has("fields")) {
                JsonNode fields = args.get("fields");
                if (fields.isObject()) {
                    Iterator<String> fieldNames = fields.fieldNames();
                    int fieldCount = 0;
                    
                    while (fieldNames.hasNext() && fieldCount < 3) { // 限制显示前3个字段
                        String fieldName = fieldNames.next();
                        JsonNode fieldInfo = fields.get(fieldName);
                        
                        if (fieldInfo.isObject() && fieldInfo.has("description") && fieldInfo.has("value")) {
                            String description = fieldInfo.get("description").asText();
                            String value = fieldInfo.get("value").toString();
                            
                            // 清理JSON字符串，移除多余的引号
                            value = value.replaceAll("^\"|\"$", "");
                            
                            formatted.append(description).append(": ").append(value);
                            
                            if (fieldNames.hasNext() && fieldCount < 2) {
                                formatted.append(", ");
                            }
                            fieldCount++;
                        }
                    }
                    
                    if (fieldNames.hasNext()) {
                        formatted.append(" 等...");
                    }
                }
            } else {
                // 尝试直接提取参数值
                Iterator<String> argNames = args.fieldNames();
                int argCount = 0;
                
                while (argNames.hasNext() && argCount < 3) {
                    String argName = argNames.next();
                    if (!argName.equals("tableName")) {
                        String value = args.get(argName).toString();
                        value = value.replaceAll("^\"|\"$", "");
                        
                        formatted.append(argName).append(": ").append(value);
                        
                        if (argNames.hasNext() && argCount < 2) {
                            formatted.append(", ");
                        }
                        argCount++;
                    }
                }
                
                if (argNames.hasNext()) {
                    formatted.append(" 等...");
                }
            }
        } else if (jsonNode.has("queryParams")) {
            // 处理查询参数
            JsonNode queryParams = jsonNode.get("queryParams");
            if (queryParams.isObject()) {
                Iterator<String> paramNames = queryParams.fieldNames();
                int paramCount = 0;
                
                formatted.append("查询条件: ");
                
                while (paramNames.hasNext() && paramCount < 3) {
                    String paramName = paramNames.next();
                    String value = queryParams.get(paramName).toString();
                    value = value.replaceAll("^\"|\"$", "");
                    
                    formatted.append(paramName).append("=").append(value);
                    
                    if (paramNames.hasNext() && paramCount < 2) {
                        formatted.append(", ");
                    }
                    paramCount++;
                }
                
                if (paramNames.hasNext()) {
                    formatted.append(" 等...");
                }
            }
        }
        
        return formatted.toString();
    }

    @Override
    public Map<String, Object> getDetailedPatientBackupInfo(Integer patientId, Integer doctorId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (patientId == null) {
                throw new IllegalArgumentException("患者ID不能为空");
            }
            
            // 获取患者基本信息 - 但不要求患者必须存在于主表
            Map<String, Object> patientInfo = getPatientInfo(patientId);
            // 即使患者不存在于主表，也继续查询备份表
            if (patientInfo != null) {
                result.put("patientInfo", patientInfo);
            } else {
                // 如果主表没有患者信息，创建一个基本的信息结构
                Map<String, Object> basicInfo = new HashMap<>();
                basicInfo.put("patientId", patientId);
                basicInfo.put("name", "未知 (仅存在于备份)");
                result.put("patientInfo", basicInfo);
            }
            
            // 获取备份表列表
            List<Map<String, String>> backupTables = getBackupTablesList();
            
            // 标记是否在任何备份表中找到患者数据
            boolean foundInAnyTable = false;
            
            // 为每个备份表获取数据并组织成 表名->数据 的映射
            Map<String, Object> tableDataMap = new HashMap<>();
            
            for (Map<String, String> table : backupTables) {
                Map<String, Object> tableData = new HashMap<>();
                String tableName = table.get("name");
                String originalName = table.get("originalName");
                String description = table.get("description");
                
                tableData.put("tableName", tableName);
                tableData.put("originalName", originalName);
                tableData.put("description", description);
                
                // 获取该表的备份记录数量
                long recordCount = backupDataMapper.countBackupData(
                    tableName,
                    patientId,
                    null, // operationType
                    null, // startTime
                    null  // endTime
                );
                tableData.put("recordCount", recordCount);
                
                // 如果找到了记录，标记为找到了患者数据
                if (recordCount > 0) {
                    foundInAnyTable = true;
                }
                
                // 获取该表的备份记录（最多获取5条最新记录）
                List<Map<String, Object>> records = new ArrayList<>();
                
                switch (tableName) {
                    case "patient_info_backup":
                        records = backupDataMapper.selectPatientInfoBackups(
                            patientId, null, null, null, 0, 5);
                        break;
                    case "diagnosis_records_backup":
                        records = backupDataMapper.selectDiagnosisRecordsBackups(
                            patientId, null, null, null, 0, 5);
                        break;
                    case "examination_items_backup":
                        records = backupDataMapper.selectExaminationItemsBackups(
                            patientId, null, null, null, 0, 5);
                        break;
                    case "treatment_plans_backup":
                        records = backupDataMapper.selectTreatmentPlansBackups(
                            patientId, null, null, null, 0, 5);
                        break;
                    case "discharge_records_backup":
                        records = backupDataMapper.selectDischargeRecordsBackups(
                            patientId, null, null, null, 0, 5);
                        break;
                }
                
                tableData.put("records", records);
                
                // 如果有记录，添加最后更新时间
                if (records != null && !records.isEmpty()) {
                    foundInAnyTable = true;
                    // 获取最后更新时间
                    if (records.get(0).containsKey("update_time")) {
                        tableData.put("lastUpdateTime", records.get(0).get("update_time"));
                    } else if (records.get(0).containsKey("backup_time")) {
                        tableData.put("lastUpdateTime", records.get(0).get("backup_time"));
                    }
                    
                    // 如果这是patient_info_backup表且主表没有患者信息，使用备份表数据补充患者信息
                    if (tableName.equals("patient_info_backup") && patientInfo == null) {
                        Map<String, Object> backupPatientInfo = records.get(0);
                        if (backupPatientInfo != null) {
                            Map<String, Object> enhancedInfo = new HashMap<>();
                            enhancedInfo.put("patientId", patientId);
                            enhancedInfo.put("name", backupPatientInfo.getOrDefault("name", "未知"));
                            if (backupPatientInfo.containsKey("age")) enhancedInfo.put("age", backupPatientInfo.get("age"));
                            if (backupPatientInfo.containsKey("gender")) enhancedInfo.put("gender", backupPatientInfo.get("gender"));
                            if (backupPatientInfo.containsKey("diagnosis")) enhancedInfo.put("diagnosis", backupPatientInfo.get("diagnosis"));
                            enhancedInfo.put("fromBackup", true);
                            result.put("patientInfo", enhancedInfo);
                        }
                    }
                }
                
                // 将该表数据添加到表映射中
                tableDataMap.put(originalName, tableData);
            }
            
            // 如果在所有备份表中都没有找到患者数据，则抛出异常
            if (!foundInAnyTable) {
                throw new IllegalArgumentException("在任何备份表中都未找到患者 ID " + patientId + " 的数据");
            }
            
            // 添加所有表数据到结果
            result.put("tableDataMap", tableDataMap);
            
            // 保留原来的tablesData数组格式以兼容现有前端
            List<Map<String, Object>> tablesData = new ArrayList<>();
            for (Object value : tableDataMap.values()) {
                if (value instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> tableData = (Map<String, Object>) value;
                    tablesData.add(tableData);
                }
            }
            result.put("tablesData", tablesData);
            
            // 添加医生信息（如果提供）
            if (doctorId != null) {
                result.put("doctorInfo", getDoctorInfo(doctorId));
            }
            
            // 获取最近的操作日志
            Map<String, Object> recentLogs = getBackupOperationLogs(
                null, // doctorId
                patientId,
                null, // tableName
                null, // operationType
                null, // startTime
                null, // endTime
                1,    // page
                5     // size - 获取前5条操作日志
            );
            
            result.put("recentOperations", recentLogs.get("logs"));
            
            return result;
        } catch (Exception e) {
            logger.error("获取患者详细备份信息失败", e);
            throw new RuntimeException("获取患者详细备份信息失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getPatientRawBackupData(Integer patientId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (patientId == null) {
                throw new IllegalArgumentException("患者ID不能为空");
            }
            
            // 定义所有备份表及其描述的映射
            Map<String, String> tableMap = new HashMap<>();
            tableMap.put("patient_info_backup", "患者基本信息备份表");
            tableMap.put("diagnosis_records_backup", "患者诊断记录备份表");
            tableMap.put("examination_items_backup", "检查项目记录备份表");
            tableMap.put("treatment_plans_backup", "治疗项目记录备份表");
            tableMap.put("discharge_records_backup", "出院建议记录备份表");
            
            // 查询患者基本信息备份表
            List<Map<String, Object>> patientInfoBackups = backupDataMapper.selectPatientInfoBackups(
                patientId, null, null, null, 0, Integer.MAX_VALUE);
            Map<String, Object> patientInfoTable = new HashMap<>();
            patientInfoTable.put("tableName", "patient_info_backup");
            patientInfoTable.put("tableDescription", "患者基本信息备份表");
            patientInfoTable.put("data", patientInfoBackups);
            result.put("patient_info_backup", patientInfoTable);
            
            // 查询诊断记录备份表
            List<Map<String, Object>> diagnosisRecordsBackups = backupDataMapper.selectDiagnosisRecordsBackups(
                patientId, null, null, null, 0, Integer.MAX_VALUE);
            Map<String, Object> diagnosisTable = new HashMap<>();
            diagnosisTable.put("tableName", "diagnosis_records_backup");
            diagnosisTable.put("tableDescription", "患者诊断记录备份表");
            diagnosisTable.put("data", diagnosisRecordsBackups);
            result.put("diagnosis_records_backup", diagnosisTable);
            
            // 查询检查项目备份表
            List<Map<String, Object>> examinationItemsBackups = backupDataMapper.selectExaminationItemsBackups(
                patientId, null, null, null, 0, Integer.MAX_VALUE);
            Map<String, Object> examinationTable = new HashMap<>();
            examinationTable.put("tableName", "examination_items_backup");
            examinationTable.put("tableDescription", "检查项目记录备份表");
            examinationTable.put("data", examinationItemsBackups);
            result.put("examination_items_backup", examinationTable);
            
            // 查询治疗计划备份表
            List<Map<String, Object>> treatmentPlansBackups = backupDataMapper.selectTreatmentPlansBackups(
                patientId, null, null, null, 0, Integer.MAX_VALUE);
            Map<String, Object> treatmentTable = new HashMap<>();
            treatmentTable.put("tableName", "treatment_plans_backup");
            treatmentTable.put("tableDescription", "治疗项目记录备份表");
            treatmentTable.put("data", treatmentPlansBackups);
            result.put("treatment_plans_backup", treatmentTable);
            
            // 查询出院建议备份表
            List<Map<String, Object>> dischargeRecordsBackups = backupDataMapper.selectDischargeRecordsBackups(
                patientId, null, null, null, 0, Integer.MAX_VALUE);
            Map<String, Object> dischargeTable = new HashMap<>();
            dischargeTable.put("tableName", "discharge_records_backup");
            dischargeTable.put("tableDescription", "出院建议记录备份表");
            dischargeTable.put("data", dischargeRecordsBackups);
            result.put("discharge_records_backup", dischargeTable);
            
            // 提供表信息列表，方便前端遍历
            List<Map<String, String>> tableList = new ArrayList<>();
            for (Map.Entry<String, String> entry : tableMap.entrySet()) {
                Map<String, String> tableInfo = new HashMap<>();
                tableInfo.put("tableName", entry.getKey());
                tableInfo.put("tableDescription", entry.getValue());
                tableList.add(tableInfo);
            }
            result.put("tableList", tableList);
            
            return result;
        } catch (Exception e) {
            logger.error("获取患者备份表原始数据失败", e);
            throw new RuntimeException("获取患者备份表原始数据失败: " + e.getMessage());
        }
    }
} 